package com.dsp.soundscape.server;

import java.io.File;
import java.util.logging.Logger;

import com.dsp.soundscape.model.AlbumInfo;
import com.dsp.soundscape.util.ImageShrinker;
import com.dsp.soundscape.util.QueryData;

public class ThumbnailScanner extends AbstractScanner {
	private static Logger log = Logger.getLogger(ThumbnailScanner.class.toString());
	
	private int size = 175;
	
	@Override
	protected void fileHandler(AlbumInfo info, File[] files, File parentDir) {
		File thumbs = new File(configuration.getConfiguration().getThumbnails().getDir());
		if (!thumbs.exists()) {
			log.info("Creating Thumbnail Directory: " + configuration.getConfiguration().getThumbnails().getDir());
			thumbs.mkdirs();
		}
		
		for (File file : files) {
			String fnlc = file.getName().toLowerCase();
			
			if ((fnlc.endsWith(".jpg") || fnlc.endsWith(".jpeg")) && info.getImage() == null) {
				info.setImage(configuration.getUriroot() + "/" + QueryData.encode(info.getFullpath(), "UTF-8") + "/" + 
						QueryData.encode(file.getName(), "UTF-8"));
				info.setImagepath(file.getName());
			} 
		}
		
		if (info.getImagepath() != null) {
			String thumbfn = info.getId().replace("/", "-") + "-" + size + "x" + size + ".thumbnail.jpg";
			String thumbfile = configuration.getConfiguration().getThumbnails().getDir() + "/" + thumbfn;
			File thumb = new File(thumbfile);
			
			if (!thumb.exists()) {
				try {
					log.info("Creating Thumbnail: " + thumbfn);
					ImageShrinker.scale(parentDir + "/" + info.getImagepath(), size, size, thumbfile);
				} catch (Exception ex) {
					info.setThumb(thumbfn);
				}
			} 
			
			if (info.getThumb() == null) {
				info.setThumb(configuration.getConfiguration().getThumbnails().getApache() + "/" + 
						QueryData.encode(thumbfn, "UTF-8"));
			}
		}
	}
}